<script lang="ts">
  import { type NodeProps } from "@xyflow/svelte";
  import NodeWrap from "../common/NodeWrap.svelte";
  import type { ExDrawNodeInfo } from "$lib/api/board/board_draw";
  import type { Action } from "svelte/action";

  //不要使用tauri的http插件的fetch,使用浏览器的fetch函数

  const props: NodeProps = $props();

  const nodeInfo = $derived(props.data as ExDrawNodeInfo);

  async function loadSvgData(node: HTMLElement) {
    const svgs = node.getElementsByTagName("svg");
    if (svgs.length == 1) {
      svgs[0].style.width = "100%";
      svgs[0].style.height = "100%";
      svgs[0].style.strokeWidth = `${nodeInfo.node_style.border_width.replace("border-", "")}px`;
      return;
    }
    const url = `/icons/board/draw/svg/${nodeInfo.content.BasicSvgContent?.svg_id ?? ""}.svg`;
    const res = await fetch(url);
    if (res.status == 200) {
      node.innerHTML = await res.text();
      const svgs = node.getElementsByTagName("svg");
      if (svgs.length == 1) {
        svgs[0].style.width = "100%";
        svgs[0].style.height = "100%";
        svgs[0].style.strokeWidth = `${nodeInfo.node_style.border_width.replace("border-", "")}px`;
      }
    }
  }

  const svgAction: Action = (node: HTMLElement) => {
    $effect(() => {
      loadSvgData(node);
    });
  };
</script>

<NodeWrap
  nodeProps={props}
  showBorder={false}
  showBgColor={true}
  showResizer
  keepAspectRatio
>
  <div class={`${nodeInfo.node_style.font_color}`} use:svgAction></div>
</NodeWrap>
